﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using JHoelsch.DataClases.DataBase;
using JHoelsch.Gui.View.View;
namespace JHoelsch.Gui.View
{
    public partial class MainWindow
    {
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {               
            this.WindowState = Properties.Settings.Default.windowState;
            if (Properties.Settings.Default.windowPosition.X != Int32.MinValue && Properties.Settings.Default.windowPosition.Y != Int32.MinValue)
            {
                this.Top = Properties.Settings.Default.windowPosition.Y;
                this.Left = Properties.Settings.Default.windowPosition.X;
            }
            this.Height = Properties.Settings.Default.windowSize.Height;
            this.Width = Properties.Settings.Default.windowSize.Width;

            StatusBarInfoLabel.Text = "Bereit...";
            StatusBarTimeLabel.Text = System.DateTime.Now.ToLongTimeString();
            StatusBarDateLabel.Text = System.DateTime.Today.ToLongDateString();
            System.Windows.Threading.DispatcherTimer timer = new System.Windows.Threading.DispatcherTimer();
            timer.Interval = TimeSpan.FromMilliseconds(100);
            timer.Tick += new EventHandler(timer_Tick);
            timer.Start();
            if (Properties.Settings.Default.openCars == null) Properties.Settings.Default.openCars = new System.Collections.Specialized.StringCollection();
            dataHolderInstance.initialiazeData(Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData) + @"\jhoelsch\spritverbrauch\", Properties.Settings.Default.openCars);
            updateActiveCar();
            Car test = JHoelsch.DataClases.Serialization.BinarySerializationTool.readFromFile<Car>(@"d:cartest.obj");
            if(test !=null)
                /*
                new SaveTestObj();
            test.Name = "mytestFileName";
            test.HasChanges = false;
                 * */
            System.Diagnostics.Debug.WriteLine(test.Id + " "+test.Name);
            //test.save(@"d:\test.obj");

            
        }                               
        private void MenuItemOpen_Click(object sender, RoutedEventArgs e)
        {
            openFileDialog.Title = "File auswählen";
            openFileDialog.DefaultExt = "xml";
            openFileDialog.Filter = "xml files (*.xml)|*.xml";
            openFileDialog.Multiselect = true;
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    Car loadedCar;
                    foreach (string filename in openFileDialog.FileNames)
                    {
                        loadedCar = Car.load<Car>(filename);
                        if (loadedCar != null)
                        {
                            loadedCar.Color = getColor();
                            CarList.Add(loadedCar);
                            ActiveCar = loadedCar;
                        }
                    }   
                }
                catch (Exception ex)
                {
                    MessageBox.Show("error during file load");
                    System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                }
            }            
        }                          
        private void MainWindowForm_Closing(object sender, System.ComponentModel.CancelEventArgs e)
        {
            Properties.Settings.Default.openCars.Clear();
            while (CarList.Count > 0)
            {
                Car car = CarList.First<Car>();
                CarList.Remove(car);
                car.save();
                Properties.Settings.Default.openCars.Add(car.FilenameWithPath);
            }
            Properties.Settings.Default.windowSize = new System.Drawing.Size((int)this.ActualWidth, (int)this.Height);
            System.Drawing.Point toSet = new System.Drawing.Point();
            toSet.Y = (int)this.Top;
            toSet.X = (int)this.Left;
            Properties.Settings.Default.windowPosition = toSet;   
            Properties.Settings.Default.Save();
        }
        private void CarButton_Click(object sender, RoutedEventArgs e)
        {
            Button btn = sender as Button;
            ActiveCar = btn.DataContext as Car;              
        }
        private void CarLeftMouseUp(object sender, MouseButtonEventArgs e)
        {
            CarButton btn = sender as CarButton;
            ActiveCar = btn.DataContext as Car;
        }
        private void SaveCar_Click(object sender, RoutedEventArgs e)
        {
            MenuItem _sender = sender as MenuItem;
            CarButton btn = ((ContextMenu)_sender.Parent).PlacementTarget as CarButton;
            Car toSave = ((Car)btn.DataContext);     
            toSave.save();

        }      
        private void SaveAsCar_Click(object sender, RoutedEventArgs e)
        {
            MenuItem _sender = sender as MenuItem;
            CarButton btn = ((ContextMenu)_sender.Parent).PlacementTarget as CarButton;
            Car toSave = ((Car)btn.DataContext);
            saveFileDialog.Title = "File auswählen";
            saveFileDialog.DefaultExt = "xml";
            saveFileDialog.Filter = "xml files (*.xml)|*.xml";
            if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                toSave.FilenameWithPath = saveFileDialog.FileName;
                toSave.save();
            }

        }     
        private void CloseCar_Click(object sender, RoutedEventArgs e)
        {
            MenuItem _sender = sender as MenuItem;
            CarButton btn = ((ContextMenu)_sender.Parent).PlacementTarget as CarButton;
            Car toClose  = ((Car)btn.DataContext);
            if (toClose.HasChanges &&
                MessageBox.Show(toClose.Name + " has unsaved Changes, save now ? ", "Confirmation",
                MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                toClose.save();
            }
            CarList.Remove(toClose);
            if (ActiveCar.Equals(toClose))
            {
                updateActiveCar();
            }

        }       
        private void MenuItemImportCars_Click(object sender, RoutedEventArgs e)
        {
            openFileDialog.Title = "File zum importieren auswählen";
            openFileDialog.DefaultExt = "dat";
            openFileDialog.Filter = "datFiles (*.dat)|*.dat|xml files (*.xml)|*.xml";
            if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                try
                {
                    Car importedCar;
                    char[] charForTrim = { '\"' };
                    string[] firstLineValues;
                    TankQuittung tankquittungToAdd;
                    foreach (string filename in openFileDialog.FileNames)
                    {
                        importedCar = new Car();
                        importedCar.FilenameWithPath = filename.Remove(filename.LastIndexOf('.'));
                        importedCar.FilenameWithPath += (".xml");
                        foreach (string line in System.IO.File.ReadLines(filename))
                        {
                            firstLineValues = line.Split(',');
                            if (firstLineValues.Length > 1)
                            {
                                //info line

                                importedCar.Name = firstLineValues[0].Trim(charForTrim);
                                importedCar.Kennzeichen = firstLineValues[1].Trim(charForTrim);
                                string date = firstLineValues[2].Trim(charForTrim);
                                int year = Int32.Parse(date.Substring(4)) + 2000;
                                int month = Int32.Parse(date.Substring(2, 2));
                                int day = Int32.Parse(date.Substring(0, 2));
                                importedCar.KaufDatum = new DateTime(year, month, day);
                                importedCar.Fahrgestellnummer = firstLineValues[6].Trim(charForTrim);
                                importedCar.ErsteKmStand = Int32.Parse(firstLineValues[8].Trim(charForTrim));
                            }
                            else
                            {
                                string tankvorgangdaten = line.Trim(charForTrim);
                                string dateAndKm = line.Substring(1, line.IndexOf(' ') - 1).Trim();
                                int year = Int32.Parse(dateAndKm.Substring(0, 2)) + 2000;
                                int month = Int32.Parse(dateAndKm.Substring(2, 2));
                                int day = Int32.Parse(dateAndKm.Substring(4, 2));
                                string liter = line.Substring(14, line.IndexOf(' ', 14) - 14).Trim();
                                string euro = line.Substring(22, line.IndexOf(' ', 22) - 22).Trim();
                                string tankstellenName = line.Substring(31, 16).Trim();
                                TankStelle tankstelle = dataHolderInstance.Tankstellen.FirstOrDefault(obj => obj.Name.StartsWith(tankstellenName, StringComparison.CurrentCultureIgnoreCase));
                                if (tankstelle == null)
                                {
                                    tankstelle = new TankStelle();
                                    tankstelle.Name = tankstellenName;

                                    tankstelle.Id = Guid.NewGuid();
                                    dataHolderInstance.Tankstellen.Add(tankstelle);
                                }
                                tankquittungToAdd = new TankQuittung();
                                tankquittungToAdd.Euro = Convert.ToDouble(euro, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
                                tankquittungToAdd.Liter = Convert.ToDouble(liter, System.Globalization.CultureInfo.InvariantCulture.NumberFormat);
                                tankquittungToAdd.Datum = new DateTime(year, month, day);
                                tankquittungToAdd.KMStand = Convert.ToInt32(dateAndKm.Substring(6));
                                tankquittungToAdd.Tankstelle = tankstelle;
                                importedCar.Tankquittungen.Add(tankquittungToAdd);
                            }
                        }
                        JHoelsch.DataClases.Serialization.XmlSerializationTool.writeToFile(importedCar, importedCar.FilenameWithPath);
                        importedCar.Color = this.getColor();
                        CarList.Add(importedCar);
                        ActiveCar = importedCar;
                    }
                }
                catch (Exception ex)
                {
                    MessageBox.Show("error during import");
                    System.Diagnostics.Debug.WriteLine(ex.StackTrace);
                }
            }
        }  
    }
}
